//--Plugins
// Grid column plugin that does the complete/active button in the left-most column
CompleteColumn = function(){
    var grid;

    function getRecord(t){
        var index = grid.getView().findRowIndex(t);
        return grid.store.getAt(index);
    }

    function onMouseDown(e, t){
        if(Ext.fly(t).hasClass('task-check')){
            e.stopEvent();
            var record = getRecord(t);
            record.set('complete', !record.data.complete);
            //grid.store.applyFilter();
        }
    }

    function onMouseOver(e, t){
        if(Ext.fly(t).hasClass('task-check')){
            Ext.fly(t.parentNode).addClass('task-check-over');
        }
    }

    function onMouseOut(e, t){
        if(Ext.fly(t).hasClass('task-check')){
            Ext.fly(t.parentNode).removeClass('task-check-over');
        }
    }

    Ext.apply(this, {
        width: 22,
        header: '<div class="task-col-hd"></div>',
        menuDisabled:true,
        fixed: true,
        id: 'task-col',
        renderer: function(){
            return '<div class="task-check"></div>';
        },
        init : function(xg){
            grid = xg;
            grid.on('render', function(){
                var view = grid.getView();
                view.mainBody.on('mousedown', onMouseDown);
                view.mainBody.on('mouseover', onMouseOver);
                view.mainBody.on('mouseout', onMouseOut);
            });
        }
    });
}; //End of completedColumn

//--StarMenu
Ext.namespace("Ext.ux");

Ext.ux.StartMenu = Ext.extend(Ext.menu.Menu, {
    initComponent: function(config) {
    	Ext.ux.StartMenu.superclass.initComponent.call(this, config);

        var tools = this.toolItems;
        this.toolItems = new Ext.util.MixedCollection();
        if(tools){
            this.addTool.apply(this, tools);
        }
    },

    // private
    onRender : function(ct, position){
        Ext.ux.StartMenu.superclass.onRender.call(this, ct, position);
        var el = this.el.addClass('ux-start-menu');

        var header = el.createChild({
        	tag: "div",
        	cls: "x-window-header x-unselectable x-panel-icon "+this.iconCls
        });

		this.header = header;

		var headerText = header.createChild({
			tag: "span",
			cls: "x-window-header-text"
		});
		var tl = header.wrap({
			cls: "ux-start-menu-tl"
		});
		var tr = header.wrap({
			cls: "ux-start-menu-tr"
		});
		var tc = header.wrap({
			cls: "ux-start-menu-tc"
		});

		this.menuBWrap = el.createChild({
			tag: "div",
			cls: "x-window-body x-border-layout-ct ux-start-menu-body"
		});
		var ml = this.menuBWrap.wrap({
			cls: "ux-start-menu-ml"
		});
		var mc = this.menuBWrap.wrap({
			cls: "x-window-mc ux-start-menu-bwrap"
		});

		this.menuPanel = this.menuBWrap.createChild({
			tag: "div",
			cls: "x-panel x-border-panel ux-start-menu-apps-panel"
		});
		this.toolsPanel = this.menuBWrap.createChild({
			tag: "div",
			cls: "x-panel x-border-panel ux-start-menu-tools-panel"
		});

		var bwrap = ml.wrap({cls: "x-window-bwrap"});
		var bc = bwrap.createChild({
			tag: "div",
			cls: "ux-start-menu-bc"
		});
		var bl = bc.wrap({
			cls: "ux-start-menu-bl x-panel-nofooter"
		});
		var br = bc.wrap({
			cls: "ux-start-menu-br"
		});

        this.ul.appendTo(this.menuPanel);

        var toolsUl = this.toolsPanel.createChild({
        	tag: "ul",
        	cls: "x-menu-list"
        });

        this.mon(toolsUl, 'click', this.onClick, this);
        this.mon(toolsUl, 'mouseover', this.onMouseOver, this);
        this.mon(toolsUl, 'mouseout', this.onMouseOut, this);

        this.items.each(function(item){
            item.parentMenu = this;
        }, this);

        this.toolItems.each(
        	function(item){
	            var li = document.createElement("li");
	            li.className = "x-menu-list-item";
	            toolsUl.dom.appendChild(li);
	            item.render(li);
                item.parentMenu = this;
	        }, this);

        this.toolsUl = toolsUl;

        this.menuBWrap.setStyle('position', 'relative');
        this.menuBWrap.setHeight(this.height - 28);

        this.menuPanel.setStyle({
        	padding: '2px',
        	position: 'absolute',
        	overflow: 'auto'
        });

        this.toolsPanel.setStyle({
        	padding: '2px 4px 2px 2px',
        	position: 'absolute',
        	overflow: 'auto'
        });

        this.setTitle(this.title);
    },

    // private
    findTargetItem : function(e){
        var t = e.getTarget(".x-menu-list-item", this.ul,  true);
        if(t && t.menuItemId){
        	if(this.items.get(t.menuItemId)){
            	return this.items.get(t.menuItemId);
            }else{
            	return this.toolItems.get(t.menuItemId);
            }
        }
    },

    /**
     * Displays this menu relative to another element
     * @param {Mixed} element The element to align to
     * @param {String} position (optional) The {@link Ext.Element#alignTo} anchor position to use in aligning to
     * the element (defaults to this.defaultAlign)
     * @param {Ext.ux.StartMenu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
     */
    show : function(el, pos, parentMenu){
        this.parentMenu = parentMenu;
        if(!this.el){
            this.render();
        }

        this.fireEvent("beforeshow", this);
        this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
        var tPanelWidth = 100;
        var box = this.menuBWrap.getBox();
        this.menuPanel.setWidth(box.width-tPanelWidth);
        this.menuPanel.setHeight(box.height);

        this.toolsPanel.setWidth(tPanelWidth);
        this.toolsPanel.setX(box.x+box.width-tPanelWidth);
        this.toolsPanel.setHeight(box.height);
    },

    addTool : function(){
        var a = arguments, l = a.length, item;
        for(var i = 0; i < l; i++){
            var el = a[i];
            if(el.render){ // some kind of Item
                item = this.addToolItem(el);
            }else if(typeof el == "string"){ // string
                if(el == "separator" || el == "-"){
                    item = this.addToolSeparator();
                }else{
                    item = this.addText(el);
                }
            }else if(el.tagName || el.el){ // element
                item = this.addElement(el);
            }else if(typeof el == "object"){ // must be menu item config?
                item = this.addToolMenuItem(el);
            }
        }
        return item;
    },

    /**
     * Adds a separator bar to the Tools
     * @return {Ext.menu.Item} The menu item that was added
     */
    addToolSeparator : function(){
        return this.addToolItem(new Ext.menu.Separator({itemCls: 'ux-toolmenu-sep'}));
    },

    addToolItem : function(item){
        this.toolItems.add(item);
        if(this.ul){
            var li = document.createElement("li");
            li.className = "x-menu-list-item";
            this.ul.dom.appendChild(li);
            item.render(li, this);
            this.delayAutoWidth();
        }
        return item;
    },

    addToolMenuItem : function(config){
        if(!(config instanceof Ext.menu.Item)){
            if(typeof config.checked == "boolean"){ // must be check menu item config?
                config = new Ext.menu.CheckItem(config);
            }else{
                config = new Ext.menu.Item(config);
            }
        }
        return this.addToolItem(config);
    },

    setTitle : function(title, iconCls){
        this.title = title;
        this.header.child('span').update(title);
        return this;
    }
});

//--TaskBar

Ext.ux.TaskBar = function(app){
    this.app = app;
    this.init();
}

Ext.extend(Ext.ux.TaskBar, Ext.util.Observable, {
    init : function(){
        this.startMenu = new Ext.ux.StartMenu(Ext.apply({
            iconCls: 'user',
            height: 300,
            shadow: true,
            title: 'Mobimin',
            width: 300
        }, this.app.startConfig));

        this.startBtn = new Ext.Button({
            text: 'Start',
            id: 'ux-startbutton',
            iconCls:'start',
            menu: this.startMenu,
            menuAlign: 'bl-tl',
            renderTo: 'ux-taskbar-start',
            clickEvent: 'mousedown',
            template: new Ext.Template(
                '<table cellspacing="0" class="x-btn"><tbody class="{1}"><tr>',
                '<td class="ux-startbutton-left"><i>&#160;</i></td>',
                '<td class="ux-startbutton-center"><em class="{2} unselectable="on">',
                    '<button class="x-btn-text" type="{0}" style="height:30px;"></button>',
                '</em></td>',
                '<td class="ux-startbutton-right"><i>&#160;</i></td>',
                '</tr></tbody></table>')
        });

        var width = this.startBtn.getEl().getWidth()+10;

        var sbBox = new Ext.BoxComponent({
            el: 'ux-taskbar-start',
            id: 'TaskBarStart',
            minWidth: width,
            region:'west',
            split: true,
            width: width
        });

        this.tbPanel = new Ext.ux.TaskButtonsPanel({
            el: 'ux-taskbuttons-panel',
            id: 'TaskBarButtons',
            region:'center'
        });
		
		this.trayPanel = new Ext.Panel(Ext.apply({
            region: 'east',
			id:'TrayPanel',
			width:150,
			bodyCfg: {cls: 'ux-taskbar-tray' },
			layout:'table',
			layoutConfig: {
				align: 'top',
				padding:0,
				columns:3
			},
			items: [
				{
					xtype:'button',
					icon:'images/signal/signal04.png',
					menu: {
						items: [
							{text:'increase', hideOnClick:false},
							{xtype:'slider', vertical:true, height:100, plugins: new Ext.slider.Tip()}
						]
					}
				},
				{
					xtype:'button',
						icon:'images/signal/wifi-on.png',
						menu: {
						items: [
							{text:'increase', hideOnClick:false},
							{xtype:'slider', vertical:true, height:100, plugins: new Ext.slider.Tip()}
						]
					}
				},
				{xtype:'button', icon:'images/signal/battery.png' }
			]
        }));
		
		var container = new Ext.ux.TaskBarContainer({
            el: 'ux-taskbar',
            layout: 'border',
            items: [sbBox,this.tbPanel,this.trayPanel]
        });

        return this;
    },

    addTaskButton : function(win){
        return this.tbPanel.addButton(win, 'ux-taskbuttons-panel');
    },

    removeTaskButton : function(btn){
        this.tbPanel.removeButton(btn);
    },

    setActiveButton : function(btn){
        this.tbPanel.setActiveButton(btn);
    }
});



/**
 * @class Ext.ux.TaskBarContainer
 * @extends Ext.Container
 */
Ext.ux.TaskBarContainer = Ext.extend(Ext.Container, {
    initComponent : function() {
        Ext.ux.TaskBarContainer.superclass.initComponent.call(this);

        this.el = Ext.get(this.el) || Ext.getBody();
        this.el.setHeight = Ext.emptyFn;
        this.el.setWidth = Ext.emptyFn;
        this.el.setSize = Ext.emptyFn;
        this.el.setStyle({
            overflow:'hidden',
            margin:'0',
            border:'0 none'
        });
        this.el.dom.scroll = 'no';
        this.allowDomMove = false;
        this.autoWidth = true;
        this.autoHeight = true;
        Ext.EventManager.onWindowResize(this.fireResize, this);
        this.renderTo = this.el;
    },

    fireResize : function(w, h){
        this.onResize(w, h, w, h);
        this.fireEvent('resize', this, w, h, w, h);
    }
});



/**
 * @class Ext.ux.TaskButtonsPanel
 * @extends Ext.BoxComponent
 */
Ext.ux.TaskButtonsPanel = Ext.extend(Ext.BoxComponent, {
    activeButton: null,
    enableScroll: true,
    scrollIncrement: 0,
    scrollRepeatInterval: 400,
    scrollDuration: .35,
    animScroll: true,
    resizeButtons: true,
    buttonWidth: 168,
    minButtonWidth: 118,
    buttonMargin: 2,
    buttonWidthSet: false,

    initComponent : function() {
        Ext.ux.TaskButtonsPanel.superclass.initComponent.call(this);
        this.on('resize', this.delegateUpdates);
        this.items = [];

        this.stripWrap = Ext.get(this.el).createChild({
            cls: 'ux-taskbuttons-strip-wrap',
            cn: {
                tag:'ul', cls:'ux-taskbuttons-strip'
            }
        });
        this.stripSpacer = Ext.get(this.el).createChild({
            cls:'ux-taskbuttons-strip-spacer'
        });
        this.strip = new Ext.Element(this.stripWrap.dom.firstChild);

        this.edge = this.strip.createChild({
            tag:'li',
            cls:'ux-taskbuttons-edge'
        });
        this.strip.createChild({
            cls:'x-clear'
        });
    },

    addButton : function(win){
        var li = this.strip.createChild({tag:'li'}, this.edge); // insert before the edge
        var btn = new Ext.ux.TaskBar.TaskButton(win, li);

        this.items.push(btn);

        if(!this.buttonWidthSet){
            this.lastButtonWidth = btn.container.getWidth();
        }

        this.setActiveButton(btn);
        return btn;
    },

    removeButton : function(btn){
        var li = document.getElementById(btn.container.id);
        btn.destroy();
        li.parentNode.removeChild(li);

        var s = [];
        for(var i = 0, len = this.items.length; i < len; i++) {
            if(this.items[i] != btn){
                s.push(this.items[i]);
            }
        }
        this.items = s;

        this.delegateUpdates();
    },

    setActiveButton : function(btn){
        this.activeButton = btn;
        this.delegateUpdates();
    },

    delegateUpdates : function(){
        /*if(this.suspendUpdates){
            return;
        }*/
        if(this.resizeButtons && this.rendered){
            this.autoSize();
        }
        if(this.enableScroll && this.rendered){
            this.autoScroll();
        }
    },

    autoSize : function(){
        var count = this.items.length;
        var ow = this.el.dom.offsetWidth;
        var aw = this.el.dom.clientWidth;

        if(!this.resizeButtons || count < 1 || !aw){ // !aw for display:none
            return;
        }

        var each = Math.max(Math.min(Math.floor((aw-4) / count) - this.buttonMargin, this.buttonWidth), this.minButtonWidth); // -4 for float errors in IE
        var btns = this.stripWrap.dom.getElementsByTagName('button');

        this.lastButtonWidth = Ext.get(btns[0].id).findParent('li').offsetWidth;

        for(var i = 0, len = btns.length; i < len; i++) {
            var btn = btns[i];

            var tw = Ext.get(btns[i].id).findParent('li').offsetWidth;
            var iw = btn.offsetWidth;

            btn.style.width = (each - (tw-iw)) + 'px';
        }
    },

    autoScroll : function(){
        var count = this.items.length;
        var ow = this.el.dom.offsetWidth;
        var tw = this.el.dom.clientWidth;

        var wrap = this.stripWrap;
        var cw = wrap.dom.offsetWidth;
        var pos = this.getScrollPos();
        var l = this.edge.getOffsetsTo(this.stripWrap)[0] + pos;

        if(!this.enableScroll || count < 1 || cw < 20){ // 20 to prevent display:none issues
            return;
        }

        wrap.setWidth(tw); // moved to here because of problem in Safari

        if(l <= tw){
            wrap.dom.scrollLeft = 0;
            //wrap.setWidth(tw); moved from here because of problem in Safari
            if(this.scrolling){
                this.scrolling = false;
                this.el.removeClass('x-taskbuttons-scrolling');
                this.scrollLeft.hide();
                this.scrollRight.hide();
            }
        }else{
            if(!this.scrolling){
                this.el.addClass('x-taskbuttons-scrolling');
            }
            tw -= wrap.getMargins('lr');
            wrap.setWidth(tw > 20 ? tw : 20);
            if(!this.scrolling){
                if(!this.scrollLeft){
                    this.createScrollers();
                }else{
                    this.scrollLeft.show();
                    this.scrollRight.show();
                }
            }
            this.scrolling = true;
            if(pos > (l-tw)){ // ensure it stays within bounds
                wrap.dom.scrollLeft = l-tw;
            }else{ // otherwise, make sure the active button is still visible
                this.scrollToButton(this.activeButton, true); // true to animate
            }
            this.updateScrollButtons();
        }
    },

    createScrollers : function(){
        var h = this.el.dom.offsetHeight; //var h = this.stripWrap.dom.offsetHeight;

        // left
        var sl = this.el.insertFirst({
            cls:'ux-taskbuttons-scroller-left'
        });
        sl.setHeight(h);
        sl.addClassOnOver('ux-taskbuttons-scroller-left-over');
        this.leftRepeater = new Ext.util.ClickRepeater(sl, {
            interval : this.scrollRepeatInterval,
            handler: this.onScrollLeft,
            scope: this
        });
        this.scrollLeft = sl;

        // right
        var sr = this.el.insertFirst({
            cls:'ux-taskbuttons-scroller-right'
        });
        sr.setHeight(h);
        sr.addClassOnOver('ux-taskbuttons-scroller-right-over');
        this.rightRepeater = new Ext.util.ClickRepeater(sr, {
            interval : this.scrollRepeatInterval,
            handler: this.onScrollRight,
            scope: this
        });
        this.scrollRight = sr;
    },

    getScrollWidth : function(){
        return this.edge.getOffsetsTo(this.stripWrap)[0] + this.getScrollPos();
    },

    getScrollPos : function(){
        return parseInt(this.stripWrap.dom.scrollLeft, 10) || 0;
    },

    getScrollArea : function(){
        return parseInt(this.stripWrap.dom.clientWidth, 10) || 0;
    },

    getScrollAnim : function(){
        return {
            duration: this.scrollDuration,
            callback: this.updateScrollButtons,
            scope: this
        };
    },

    getScrollIncrement : function(){
        return (this.scrollIncrement || this.lastButtonWidth+2);
    },

    /* getBtnEl : function(item){
        return document.getElementById(item.id);
    }, */

    scrollToButton : function(item, animate){
        item = item.el.dom.parentNode; // li
        if(!item){ return; }
        var el = item; //this.getBtnEl(item);
        var pos = this.getScrollPos(), area = this.getScrollArea();
        var left = Ext.fly(el).getOffsetsTo(this.stripWrap)[0] + pos;
        var right = left + el.offsetWidth;
        if(left < pos){
            this.scrollTo(left, animate);
        }else if(right > (pos + area)){
            this.scrollTo(right - area, animate);
        }
    },

    scrollTo : function(pos, animate){
        this.stripWrap.scrollTo('left', pos, animate ? this.getScrollAnim() : false);
        if(!animate){
            this.updateScrollButtons();
        }
    },

    onScrollRight : function(){
        var sw = this.getScrollWidth()-this.getScrollArea();
        var pos = this.getScrollPos();
        var s = Math.min(sw, pos + this.getScrollIncrement());
        if(s != pos){
            this.scrollTo(s, this.animScroll);
        }
    },

    onScrollLeft : function(){
        var pos = this.getScrollPos();
        var s = Math.max(0, pos - this.getScrollIncrement());
        if(s != pos){
            this.scrollTo(s, this.animScroll);
        }
    },

    updateScrollButtons : function(){
        var pos = this.getScrollPos();
        this.scrollLeft[pos == 0 ? 'addClass' : 'removeClass']('ux-taskbuttons-scroller-left-disabled');
        this.scrollRight[pos >= (this.getScrollWidth()-this.getScrollArea()) ? 'addClass' : 'removeClass']('ux-taskbuttons-scroller-right-disabled');
    }
});



/**
 * @class Ext.ux.TaskBar.TaskButton
 * @extends Ext.Button
 */
Ext.ux.TaskBar.TaskButton = function(win, el){
    this.win = win;
    Ext.ux.TaskBar.TaskButton.superclass.constructor.call(this, {
        iconCls: win.iconCls,
        text: Ext.util.Format.ellipsis(win.title, 12),
        renderTo: el,
        handler : function(){
            if(win.minimized || win.hidden){
                win.show();
            }else if(win == win.manager.getActive()){
                win.minimize();
            }else{
                win.toFront();
            }
        },
        clickEvent:'mousedown',
        template: new Ext.Template(
            '<table cellspacing="0" class="x-btn {3}"><tbody><tr>',
            '<td class="ux-taskbutton-left"><i>&#160;</i></td>',
            '<td class="ux-taskbutton-center"><em class="{5} unselectable="on">',
                '<button class="x-btn-text {2}" type="{1}" style="height:28px;">{0}</button>',
            '</em></td>',
            '<td class="ux-taskbutton-right"><i>&#160;</i></td>',
            "</tr></tbody></table>")
    });
};

Ext.extend(Ext.ux.TaskBar.TaskButton, Ext.Button, {
    onRender : function(){
        Ext.ux.TaskBar.TaskButton.superclass.onRender.apply(this, arguments);

        this.cmenu = new Ext.menu.Menu({
            items: [{
                text: 'Restore',
                handler: function(){
                    if(!this.win.isVisible()){
                        this.win.show();
                    }else{
                        this.win.restore();
                    }
                },
                scope: this
            },{
                text: 'Minimize',
                handler: this.win.minimize,
                scope: this.win
            },{
                text: 'Maximize',
                handler: this.win.maximize,
                scope: this.win
            }, '-', {
                text: 'Close',
                handler: this.closeWin.createDelegate(this, this.win, true),
                scope: this.win
            }]
        });

        this.cmenu.on('beforeshow', function(){
            var items = this.cmenu.items.items;
            var w = this.win;
            items[0].setDisabled(w.maximized !== true && w.hidden !== true);
            items[1].setDisabled(w.minimized === true);
            items[2].setDisabled(w.maximized === true || w.hidden === true);
        }, this);

        this.el.on('contextmenu', function(e){
            e.stopEvent();
            if(!this.cmenu.el){
                this.cmenu.render();
            }
            var xy = e.getXY();
            xy[1] -= this.cmenu.el.getHeight();
            this.cmenu.showAt(xy);
        }, this);
    },

    closeWin : function(cMenu, e, win){
        if(!win.isVisible()){
            win.show();
        }else{
            win.restore();
        }
        win.close();
    }
});

//--Desktop.js
Ext.Desktop = function(app) {
    this.taskbar = new Ext.ux.TaskBar(app);
    this.xTickSize = this.yTickSize = 1;
    var taskbar = this.taskbar;

    var desktopEl = Ext.get('x-desktop');
    var taskbarEl = Ext.get('ux-taskbar');
    var shortcuts = Ext.get('x-shortcuts');

    var windows = new Ext.WindowGroup();
	windows.zseed=900;
    var activeWindow;

    function minimizeWin(win) {
        win.minimized = true;
        win.hide();
    }

    function markActive(win) {
        if (activeWindow && activeWindow != win) {
            markInactive(activeWindow);
        }
        taskbar.setActiveButton(win.taskButton);
        activeWindow = win;
        Ext.fly(win.taskButton.el).addClass('active-win');
        win.minimized = false;
    }

    function markInactive(win) {
        if (win == activeWindow) {
            activeWindow = null;
            Ext.fly(win.taskButton.el).removeClass('active-win');
        }
    }

    function removeWin(win) {
        taskbar.removeTaskButton(win.taskButton);
        layout();
    }

    function layout() {
        desktopEl.setHeight(Ext.lib.Dom.getViewHeight() - taskbarEl.getHeight());
    }
    Ext.EventManager.onWindowResize(layout);

    this.layout = layout;

    this.createWindow = function(config, cls) {
        var win = new(cls || Ext.Window)(
        Ext.applyIf(config || {},
        {
            renderTo: desktopEl,
            manager: windows,
            minimizable: true,
            maximizable: true
        })
        );
        win.dd.xTickSize = this.xTickSize;
        win.dd.yTickSize = this.yTickSize;
        if (win.resizer) {
            win.resizer.widthIncrement = this.xTickSize;
            win.resizer.heightIncrement = this.yTickSize;
        }
        win.render(desktopEl);
        win.taskButton = taskbar.addTaskButton(win);

        win.cmenu = new Ext.menu.Menu({
            items: [

            ]
        });

        win.animateTarget = win.taskButton.el;

        win.on({
            'activate': {
                fn: markActive
            },
            'beforeshow': {
                fn: markActive
            },
            'deactivate': {
                fn: markInactive
            },
            'minimize': {
                fn: minimizeWin
            },
            'close': {
                fn: removeWin
            }
        });

        layout();
        return win;
    };

    this.getManager = function() {
        return windows;
    };

    this.getWindow = function(id) {
        return windows.get(id);
    };

    this.getWinWidth = function() {
        var width = Ext.lib.Dom.getViewWidth();
        return width < 200 ? 200: width;
    };

    this.getWinHeight = function() {
        var height = (Ext.lib.Dom.getViewHeight() - taskbarEl.getHeight());
        return height < 100 ? 100: height;
    };

    this.getWinX = function(width) {
        return (Ext.lib.Dom.getViewWidth() - width) / 2;
    };

    this.getWinY = function(height) {
        return (Ext.lib.Dom.getViewHeight() - taskbarEl.getHeight() - height) / 2;
    };

    this.setTickSize = function(xTickSize, yTickSize) {
        this.xTickSize = xTickSize;
        if (arguments.length == 1) {
            this.yTickSize = xTickSize;
        } else {
            this.yTickSize = yTickSize;
        }
        windows.each(function(win) {
            win.dd.xTickSize = this.xTickSize;
            win.dd.yTickSize = this.yTickSize;
            win.resizer.widthIncrement = this.xTickSize;
            win.resizer.heightIncrement = this.yTickSize;
        },
        this);
    };

    this.cascade = function() {
        var x = 0,
        y = 0;
        windows.each(function(win) {
            if (win.isVisible() && !win.maximized) {
                win.setPosition(x, y);
                x += 20;
                y += 20;
            }
        },
        this);
    };

    this.tile = function() {
        var availWidth = desktopEl.getWidth(true);
        var x = this.xTickSize;
        var y = this.yTickSize;
        var nextY = y;
        windows.each(function(win) {
            if (win.isVisible() && !win.maximized) {
                var w = win.el.getWidth();

                //              Wrap to next row if we are not at the line start and this Window will go off the end
                if ((x > this.xTickSize) && (x + w > availWidth)) {
                    x = this.xTickSize;
                    y = nextY;
                }

                win.setPosition(x, y);
                x += w + this.xTickSize;
                nextY = Math.max(nextY, y + win.el.getHeight() + this.yTickSize);
            }
        },
        this);
    };

    this.contextMenu = new Ext.menu.Menu({
        items: [{
            text: 'Tile',
            handler: this.tile,
            scope: this
        },
        {
            text: 'Cascade',
            handler: this.cascade,
            scope: this
        }]
    });
    desktopEl.on('contextmenu',
        function(e) {
            e.stopEvent();
            this.contextMenu.showAt(e.getXY());
        },
        this);

    layout();

    if (shortcuts) {
        shortcuts.on('click',
        function(e, t) {
            t = e.getTarget('dt', shortcuts);
            if (t) {
                e.stopEvent();
                var module = app.getModule(t.id.replace('-shortcut', ''));
                if (module) {
                    module.createWindow();
                }
            }
        });
    }
};

//--App
Ext.app.App = function(cfg){
    Ext.apply(this, cfg);
    this.addEvents({
        'ready' : true,
        'beforeunload' : true
    });

    Ext.onReady(this.initApp, this);
};

Ext.extend(Ext.app.App, Ext.util.Observable, {
    isReady: false,
    startMenu: null,
    modules: null,

    getStartConfig : function(){

    },

    initApp : function(){
    	this.startConfig = this.startConfig || this.getStartConfig();

        this.desktop = new Ext.Desktop(this);

		this.launcher = this.desktop.taskbar.startMenu;

		this.modules = this.getModules();
        if(this.modules){
            this.initModules(this.modules);
        }

        this.init();

        Ext.EventManager.on(window, 'beforeunload', this.onUnload, this);
		this.fireEvent('ready', this);
        this.isReady = true;
    },

    getModules : Ext.emptyFn,
    init : Ext.emptyFn,

    initModules : function(ms){
		for(var i = 0, len = ms.length; i < len; i++){
            var m = ms[i];
            this.launcher.add(m.launcher);
            m.app = this;
        }
    },

    getModule : function(name){
    	var ms = this.modules;
    	for(var i = 0, len = ms.length; i < len; i++){
    		if(ms[i].id == name || ms[i].appType == name){
    			return ms[i];
			}
        }
        return '';
    },

    onReady : function(fn, scope){
        if(!this.isReady){
            this.on('ready', fn, scope);
        }else{
            fn.call(scope, this);
        }
    },

    getDesktop : function(){
        return this.desktop;
    },

    onUnload : function(e){
        if(this.fireEvent('beforeunload', this) === false){
            e.stopEvent();
        }
    }
});

//--Modules
Ext.app.Module = function(config){
    Ext.apply(this, config);
    Ext.app.Module.superclass.constructor.call(this);
    this.init();
}

Ext.extend(Ext.app.Module, Ext.util.Observable, {
    init : Ext.emptyFn
});

//--Mobimin

Ext.BLANK_IMAGE_URL = '../../resources/images/default/s.gif';

Ext.Mobimin = function(){
    var msgCt;

    function createBox(t, s){
        return ['<div class="msg">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</div>'].join('');
    }
    return {
        msg : function(title, format){
            if(!msgCt){
                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
            }
            msgCt.alignTo(document, 't-t');
            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
            m.slideIn('t').pause(2).ghost("t", {remove:true});
        },

        init : function(){
            var lb = Ext.get('lib-bar');
            if(lb){
                lb.show();
            }
        }
    };
}();

//Ext.example.bogusMarkup = '<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed metus nibh, sodales a, porta at, vulputate eget, dui. Pellentesque ut nisl. Maecenas tortor turpis, interdum non, sodales non, iaculis ac, lacus. Vestibulum auctor, tortor quis iaculis malesuada, libero lectus bibendum purus, sit amet tincidunt quam turpis vel lacus. In pellentesque nisl non sem. Suspendisse nunc sem, pretium eget, cursus a, fringilla vel, urna.<br/><br/>Aliquam commodo ullamcorper erat. Nullam vel justo in neque porttitor laoreet. Aenean lacus dui, consequat eu, adipiscing eget, nonummy non, nisi. Morbi nunc est, dignissim non, ornare sed, luctus eu, massa. Vivamus eget quam. Vivamus tincidunt diam nec urna. Curabitur velit.</p>';

Ext.onReady(Ext.Mobimin.init, Ext.Mobimin);

//--Sample (Active Application)
/*!
 * Ext JS Library 3.3.0
 * Copyright(c) 2006-2010 Ext JS, Inc.
 * licensing@extjs.com
 * http://www.extjs.com/license
 */

// Sample desktop configuration
var lockButton = new Ext.slider.SingleSlider({
	id:'lock-button',
	width:345,
	value:50,
	height:82,
	clickToChange:false,
	listeners:{
		'changecomplete':function(s,nv,t) {
							if ((nv>15) && (nv < 85)) {
								s.setValue(50);
							} else {
								loginWindow.close();
							}
						}
	}
});

var loginWindow = new Ext.Window({
	id:'login-win',
	modal:true,
	width:480,
	height:440,
	resizable:false,
	bodyBorder:false,
	border:false,
	closable:false,
	draggable:false,
	layout:'form',
	padding:60,
	items:[
		{
			xtype:'textfield',
			emptyText:'Pass-code ...',
			hideLabel:true,
			style:{
				width:'100%',
				fontSize:'18px',
				height:'35px'
			}
		},
		lockButton,
		{
			xtype:'label',
			text:'Slide to unlock ...',
			style: {
				paddingTop:'90px',
				color:'#FFFFFF',
				fontSize:'16px',
				width:'100%',
				textAlign:'center'
			}
		}
	]
});

Ext.onReady(
	function() {
		loginWindow.show();
	}
);

MyDesktop = new Ext.app.App({
	init :function(){
		Ext.QuickTips.init();
	},

	getModules : function(){
		return [
			new MyDesktop.GridWindow(),
            new MyDesktop.TabWindow(),
            new MyDesktop.AccordionWindow(),
            new MyDesktop.BogusMenuModule(),
            new MyDesktop.BogusModule(),
			new MyDesktop.CallHistory(),
			new MyDesktop.Camera(),
			new MyDesktop.FileManager(),
			new MyDesktop.RegistryEditor(),
			new MyDesktop.Outlook()
		];
	},

    // config for the start menu
    getStartConfig : function(){
        return {
            title: 'Jack Slocum',
            iconCls: 'user',
            toolItems: [{
                text:'Settings',
                iconCls:'settings',
                scope:this
            },'-',{
                text:'Logout',
                iconCls:'logout',
                scope:this
            }]
        };
    }
});



/*
 * Example windows
 */
MyDesktop.GridWindow = Ext.extend(Ext.app.Module, {
    id:'grid-win',
    init : function(){
        this.launcher = {
            text: 'Grid Window',
            iconCls:'icon-grid',
            handler : this.createWindow,
            scope: this
        }
    },

    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('grid-win');
        if(!win){
            win = desktop.createWindow({
                id: 'grid-win',
                title:'Grid Window',
                width:740,
                height:480,
                iconCls: 'icon-grid',
                shim:false,
                animCollapse:false,
                constrainHeader:true,

                layout: 'fit',
                items:
                    new Ext.grid.GridPanel({
                        border:false,
                        ds: new Ext.data.Store({
                            reader: new Ext.data.ArrayReader({}, [
                               {name: 'company'},
                               {name: 'price', type: 'float'},
                               {name: 'change', type: 'float'},
                               {name: 'pctChange', type: 'float'}
                            ]),
                            data: Ext.grid.dummyData
                        }),
                        cm: new Ext.grid.ColumnModel([
                            new Ext.grid.RowNumberer(),
                            {header: "Company", width: 120, sortable: true, dataIndex: 'company'},
                            {header: "Price", width: 70, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'price'},
                            {header: "Change", width: 70, sortable: true, dataIndex: 'change'},
                            {header: "% Change", width: 70, sortable: true, dataIndex: 'pctChange'}
                        ]),

                        viewConfig: {
                            forceFit:true
                        },
                        //autoExpandColumn:'company',

                        tbar:[{
                            text:'Add Something',
                            tooltip:'Add a new row',
                            iconCls:'add'
                        }, '-', {
                            text:'Options',
                            tooltip:'Blah blah blah blaht',
                            iconCls:'option'
                        },'-',{
                            text:'Remove Something',
                            tooltip:'Remove the selected item',
                            iconCls:'remove'
                        }]
                    })
            });
        }
        win.show();
    }
});

MyDesktop.TabWindow = Ext.extend(Ext.app.Module, {
    id:'tab-win',
    init : function(){
        this.launcher = {
            text: 'Tab Window',
            iconCls:'tabs',
            handler : this.createWindow,
            scope: this
        }
    },

    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('tab-win');
        if(!win){
            win = desktop.createWindow({
                id: 'tab-win',
                title:'Tab Window',
                width:740,
                height:480,
                iconCls: 'tabs',
                shim:false,
                animCollapse:false,
                border:false,
                constrainHeader:true,

                layout: 'fit',
                items:
                    new Ext.TabPanel({
                        activeTab:0,

                        items: [{
                            title: 'Tab Text 1',
                            header:false,
                            html : '<p>Something useful would be in here.</p>',
                            border:false
                        },{
                            title: 'Tab Text 2',
                            header:false,
                            html : '<p>Something useful would be in here.</p>',
                            border:false
                        },{
                            title: 'Tab Text 3',
                            header:false,
                            html : '<p>Something useful would be in here.</p>',
                            border:false
                        },{
                            title: 'Tab Text 4',
                            header:false,
                            html : '<p>Something useful would be in here.</p>',
                            border:false
                        }]
                    })
            });
        }
        win.show();
    }
});

MyDesktop.AccordionWindow = Ext.extend(Ext.app.Module, {
    id:'acc-win',
    init : function(){
        this.launcher = {
            text: 'Accordion Window',
            iconCls:'accordion',
            handler : this.createWindow,
            scope: this
        }
    },

    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('acc-win');
        if(!win){
            win = desktop.createWindow({
                id: 'acc-win',
                title: 'Accordion Window',
                width:250,
                height:400,
                iconCls: 'accordion',
                shim:false,
                animCollapse:false,
                constrainHeader:true,

                tbar:[{
                    tooltip:{title:'Rich Tooltips', text:'Let your users know what they can do!'},
                    iconCls:'connect'
                },'-',{
                    tooltip:'Add a new user',
                    iconCls:'user-add'
                },' ',{
                    tooltip:'Remove the selected user',
                    iconCls:'user-delete'
                }],

                layout:'accordion',
                border:false,
                layoutConfig: {
                    animate:false
                },

                items: [
                    new Ext.tree.TreePanel({
                        id:'im-tree',
                        title: 'Online Users',
                        loader: new Ext.tree.TreeLoader(),
                        rootVisible:false,
                        lines:false,
                        autoScroll:true,
                        tools:[{
                            id:'refresh',
                            on:{
                                click: function(){
                                    var tree = Ext.getCmp('im-tree');
                                    tree.body.mask('Loading', 'x-mask-loading');
                                    tree.root.reload();
                                    tree.root.collapse(true, false);
                                    setTimeout(function(){ // mimic a server call
                                        tree.body.unmask();
                                        tree.root.expand(true, true);
                                    }, 1000);
                                }
                            }
                        }],
                        root: new Ext.tree.AsyncTreeNode({
                            text:'Online',
                            children:[{
                                text:'Friends',
                                expanded:true,
                                children:[{
                                    text:'Jack',
                                    iconCls:'user',
                                    leaf:true
                                },{
                                    text:'Brian',
                                    iconCls:'user',
                                    leaf:true
                                },{
                                    text:'Jon',
                                    iconCls:'user',
                                    leaf:true
                                },{
                                    text:'Tim',
                                    iconCls:'user',
                                    leaf:true
                                },{
                                    text:'Nige',
                                    iconCls:'user',
                                    leaf:true
                                },{
                                    text:'Fred',
                                    iconCls:'user',
                                    leaf:true
                                },{
                                    text:'Bob',
                                    iconCls:'user',
                                    leaf:true
                                }]
                            },{
                                text:'Family',
                                expanded:true,
                                children:[{
                                    text:'Kelly',
                                    iconCls:'user-girl',
                                    leaf:true
                                },{
                                    text:'Sara',
                                    iconCls:'user-girl',
                                    leaf:true
                                },{
                                    text:'Zack',
                                    iconCls:'user-kid',
                                    leaf:true
                                },{
                                    text:'John',
                                    iconCls:'user-kid',
                                    leaf:true
                                }]
                            }]
                        })
                    }), {
                        title: 'Settings',
                        html:'<p>Something useful would be in here.</p>',
                        autoScroll:true
                    },{
                        title: 'Even More Stuff',
                        html : '<p>Something useful would be in here.</p>'
                    },{
                        title: 'My Stuff',
                        html : '<p>Something useful would be in here.</p>'
                    }
                ]
            });
        }
        win.show();
    }
});

// for example purposes
var windowIndex = 0;

MyDesktop.BogusModule = Ext.extend(Ext.app.Module, {
    init : function(){
        this.launcher = {
            text: 'Window '+(++windowIndex),
            iconCls:'bogus',
            handler : this.createWindow,
            scope: this,
            windowId:windowIndex
        }
    },

    createWindow : function(src){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('bogus'+src.windowId);
        if(!win){
            win = desktop.createWindow({
                id: 'bogus'+src.windowId,
                title:src.text,
                width:640,
                height:480,
                html : '<p>Something useful would be in here.</p>',
                iconCls: 'bogus',
                shim:false,
                animCollapse:false,
                constrainHeader:true
            });
        }
        win.show();
    }
});

MyDesktop.BogusMenuModule = Ext.extend(MyDesktop.BogusModule, {
    init : function(){
        this.launcher = {
            text: 'Bogus Submenu',
            iconCls: 'bogus',
            handler: function() {
				return false;
			},
            menu: {
                items:[{
                    text: 'Bogus Window '+(++windowIndex),
                    iconCls:'bogus',
                    handler : this.createWindow,
                    scope: this,
                    windowId: windowIndex
                    },{
                    text: 'Bogus Window '+(++windowIndex),
                    iconCls:'bogus',
                    handler : this.createWindow,
                    scope: this,
                    windowId: windowIndex
                    },{
                    text: 'Bogus Window '+(++windowIndex),
                    iconCls:'bogus',
                    handler : this.createWindow,
                    scope: this,
                    windowId: windowIndex
                    },{
                    text: 'Bogus Window '+(++windowIndex),
                    iconCls:'bogus',
                    handler : this.createWindow,
                    scope: this,
                    windowId: windowIndex
                    },{
                    text: 'Bogus Window '+(++windowIndex),
                    iconCls:'bogus',
                    handler : this.createWindow,
                    scope: this,
                    windowId: windowIndex
                }]
            }
        }
    }
});

MyDesktop.CallHistory = Ext.extend(Ext.app.Module, {
	id:'callhistory-win',
    init : function(){
        this.launcher = {
            text: 'Call History',
            iconCls:'bogus',
            handler : this.createWindow,
            scope: this
        }
    },

    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('callhistory-win');
        if(!win){
            win = desktop.createWindow({
                id: 'callhistory-win',
                title:'Call History',
                width:380,
                height:580,
                iconCls: 'bogus',
                shim:false,
                animCollapse:false,
                constrainHeader: true,
                layout: 'fit',
                items:
                    new Ext.TabPanel({
                        activeTab: 0,
                        items: [{ //Tabs
                            title: 'All Calls',
                            layout: 'fit',
							items: new Ext.grid.GridPanel({
								hideHeaders:true,
								loadMask:true,
                                border: false,
                                ds: dsCallHistory,
								bbar: {xtype: 'paging', pageSize:50, store: dsCallHistory,displayInfo:true},
                                cm: new Ext.grid.ColumnModel([
									{xtype:'templatecolumn', header: 'Calls', sortable: true,tpl: '<div><div style="float:left;"><img src="images/CallHistory/{callType}.png" height="32px" style="float:left;margin-right:3px;">{name}<br /><b>{number}</b></div><div style="float:right;">{startTime}<br /><b><i>Duration: {duration}</i></b></div>  </div>'}
								]),
                                viewConfig: {
                                    forceFit: true
                                },
								listeners: {'viewready': function() { if (dsCallHistory.data.length==0) { dsCallHistory.load({'start':0,'limit':50}); } } }
                                }) //End of grid
                        } //End Of Tab Call History
						, {
                            title: 'Missed Calls',
                            layout: 'fit',
                            items: new Ext.grid.GridPanel({
								hideHeaders:true,
								loadMask:true,
                                border: false,
                                ds: dsMissedCalls,
								bbar: {xtype: 'paging', pageSize:50, store: dsMissedCalls,displayInfo:true},
                                cm: new Ext.grid.ColumnModel([
									{xtype:'templatecolumn', header: 'Calls', sortable: true,tpl: '<div><div style="float:left;"><img src="images/CallHistory/missed.png" height="32px" style="float:left;margin-right:3px;">{name}<br /><b>{number}</b></div><div style="float:right;">{startTime}<br /></div>  </div>'}
								]),
                                viewConfig: {
                                    forceFit: true
                                },
								listeners: {'viewready': function() { if (dsMissedCalls.data.length==0) { dsMissedCalls.load({'start':0,'limit':50}); } } }
                                })
                        }, //End of missed calls tab
						{
                            title: 'Incoming Calls',
                            layout: 'fit',
                            items: new Ext.grid.GridPanel({
								hideHeaders:true,
								loadMask:true,
                                border: false,
                                ds: dsIncomingCalls,
								bbar: {xtype: 'paging', pageSize:50, store: dsIncomingCalls,displayInfo:true},
                                cm: new Ext.grid.ColumnModel([
									{xtype:'templatecolumn', header: 'Calls', sortable: true,tpl: '<div><div style="float:left;"><img src="images/CallHistory/incoming.png" height="32px" style="float:left;margin-right:3px;">{name}<br /><b>{number}</b></div><div style="float:right;">{startTime}<br /><b><i>Duration: {duration}</i></b></div>  </div>'}
								]),
                                viewConfig: {
                                    forceFit: true
                                },
								listeners: {'viewready': function() { if (dsIncomingCalls.data.length==0) { dsIncomingCalls.load({'start':0,'limit':50}); } } }
                                })
                        }, //End of incoming calls tab
						{
                            title: 'Outgoing Calls',
                            layout:'fit',
                            items: new Ext.grid.GridPanel({
								hideHeaders:true,
								loadMask:true,
                                border: false,
                                ds: dsOutgoingCalls,
								bbar: {xtype: 'paging', pageSize:50, store: dsOutgoingCalls,displayInfo:true},
                                cm: new Ext.grid.ColumnModel([
									{xtype:'templatecolumn', header: 'Calls', sortable: true,tpl: '<div><div style="float:left;"><img src="images/CallHistory/incoming.png" height="32px" style="float:left;margin-right:3px;">{name}<br /><b>{number}</b></div><div style="float:right;">{startTime}<br /><b><i>Duration: {duration}</i></b></div>  </div>'}
								]),
                                viewConfig: {
                                    forceFit: true
                                },
								listeners: {'viewready': function() { if (dsOutgoingCalls.data.length==0) { dsOutgoingCalls.load({'start':0,'limit':50}); } } }
                                })
                            }]
                        }) //End of tabs
            });
        }
        win.show();
    }
});

MyDesktop.Camera = Ext.extend(Ext.app.Module, {
	id:'camera-win',
    init : function(){
        this.launcher = {
            text: 'Camera',
            iconCls:'bogus',
            handler : this.createWindow,
            scope: this
        }
    },

    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('camera-win');
        if(!win){
            win = desktop.createWindow({
                id: 'camera-win',
                title:'Camera',
                width:650,
                height:500,
                iconCls: 'bogus',
                shim:false,
                animCollapse:false,
                constrainHeader: true,
				maskDisabled:false,
				html:'<b>Loading ...</b>',
				transactionId:0,
				taskMgr: {run: function() {
												win.setTitle('Camera - Loading ...');
												win.transactionId = Ext.Ajax.request({
													url: 'MOBIMIN-AJAX/CAMERA',
													success: function(response, opts) {
														var img = Ext.decode(response.responseText);
														win.setWidth(img.width+14);
														win.setHeight(img.height+32);
														win.body.update(img.src);
														win.setTitle('Camera');
													},
													failure: function(response, opts) {
														alert(response.status);
													}
												}); //End of ajax
											},
						interval: 10000, scope:this},
				listeners: {'show': function() { Ext.TaskMgr.start(this.taskMgr); }, 'close': function() { Ext.Ajax.abort(win.transactionId); Ext.TaskMgr.stop(this.taskMgr); }, 'minimize': function() { Ext.TaskMgr.stop(this.taskMgr); } },
                layout: 'fit' //,
                //items: {}
            });
        }
        win.show();
    }
}); // End of Camera window

MyDesktop.FileManager = Ext.extend(Ext.app.Module, {
	id:'filemanager-win',
    init : function(){
        this.launcher = {
            text: 'My Mobile',
            iconCls:'bogus',
            handler : this.createWindow,
            scope: this
        }
    },

    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('filemanager-win');
        if(!win){
            win = desktop.createWindow({
                id: 'filemanager-win',
                title:'My Mobile',
                width:650,
                height:380,
                iconCls: 'bogus',
                shim:false,
                animCollapse:false,
                constrainHeader: true,
				maskDisabled:false,
				layout:'border',
				listeners: {'show': function() { dsFiles.load({params:{root:"My Mobile", start:0, limit:50}}); } },
                items:[
						{
							xtype:'treepanel',
							id:'tree-folders',
							width:150,
							title:'Folders',
							autoScroll:true,
							region:'west',
							split:true,
							useArrows: true,
							dataUrl:'MOBIMIN-AJAX/FOLDERS',
							requestMethod:'GET',
							listeners: {'click': function(node,event) { dsFiles.load({params:{root:node.id,start:0, limit:50}}) } },
							root: {
								nodeType: 'async',
								text: 'My Mobile',
								id: 'My Mobile'
							}
						},
						{
							xtype:'panel',
							layout:'fit',
							title:'My Mobile',
							region:'center',
							items: [{
								xtype:'grid',
								id:'grid-files',
								tbar:{
									xtype:'toolbar',
									items:[
										{xtype:'button',id:'b-newfolder',text:'New',icon:'resources/images/access/tree/folder.gif', handler:newFolder},
										{xtype:'button',id:'b-properties',disabled:true,text:'Properties',icon:'resources/images/access/tree/leaf.gif',handler:propertyFF},
										{xtype:'button',id:'b-delete',disabled:true,text:'Delete',icon:'resources/images/access/tree/drop-no.gif', handler:deleteFF},
										{xtype:'button',id:'b-rename',disabled:true,text:'Rename',icon:'resources/images/access/tree/drop-no.gif', handler:renameFF},
										'-',
										{xtype:'button',id:'b-download',disabled:true,text:'Download',icon:'resources/images/access/tree/drop-yes.gif',handler:downloadFile},
										{xtype:'button',id:'b-upload',text:'Upload',icon:'resources/images/access/tree/drop-yes.gif',handler:uploadFile}
									]
								},
								region:'center',
								loadMask:true,
								border:false,
								autoExpandColumn:true,
								columns: [
									{xtype:'templatecolumn',fixed:true,menuDisabled:true, sortable:false, dataIndex:'icon',width:28,tpl:'<img src="images/{icon}" width="16px" />'},
									{xtype:'gridcolumn', header:'Files', sortable:true, dataIndex:'fileName'},
									{xtype:'gridcolumn', header:'Type',sortable:true,dataIndex:'type'},
									{xtype:'gridcolumn', header:'Creation Time', sortable: true, dataIndex:'creationTime',width:140},
									{xtype:'templatecolumn', header:'Size', sortable:true,align:'right', dataIndex:'size', tpl:'{[ values.type === "Folder" ? "" : fm.fileSize(values.size) ]}'}
								],
								ds:dsFiles,
								bbar: {
										xtype:'paging',
										pageSize:50,
										store: dsFiles,
										displayInfo:true,
										listeners:{'beforechange': function(p, options) { 
																	//options.params.root=store.lastOptions.root;
																	options.root=p.store.lastOptions.params.root;
																	return true;
																}
													}
										}, //End of bbar
								listeners: {
											'viewready': function(grid) {
												grid.getSelectionModel().on('rowselect', function(sm, rowIndex, r) {
													if (r.data.type=="Folder") {
															grid.toolbars[0].items.items[1].setDisabled(false);
															grid.toolbars[0].items.items[2].setDisabled(false);
															grid.toolbars[0].items.items[3].setDisabled(false);
															grid.toolbars[0].items.items[5].setDisabled(true);
															//grid.toolbars[0].items.items[6].setDisabled(true);
														} else {
															grid.toolbars[0].items.items[1].setDisabled(false);
															grid.toolbars[0].items.items[2].setDisabled(false);
															grid.toolbars[0].items.items[3].setDisabled(false);
															grid.toolbars[0].items.items[5].setDisabled(false);
															//grid.toolbars[0].items.items[6].setDisabled(false);
														}
												  });
											}, //End of view ready
											'rowdblclick': function(grid,rowIndex,e) {
														if (this.store.data.items[rowIndex].data.type=="Folder") {
															var parentFolder = this.store.lastOptions.params.root;
															var oTree = desktop.getWindow('filemanager-win').items.items[0];
															oTree.getNodeById(parentFolder).expand(false,true, function(node) {
																node.ensureVisible();
																var folder= this.store.lastOptions.params.root + "/" + this.store.data.items[rowIndex].data.fileName;
																node.ownerTree.getNodeById(node.id + "/" + this.store.data.items[rowIndex].data.fileName).select();
																this.store.load({params:{root:folder,start:0, limit:50}});
																},
																this); //End of getNodeById
														} else {
															//TODO: Open file property window
														} //End if
											} //end of rowdblclick
										} //End of grid listeners
							}]
						}
						] //End of FileManager Items
            });
        }
        win.show();
    }
}); // End of File Manager window

MyDesktop.RegistryEditor = Ext.extend(Ext.app.Module, {
	id:'registryeditor-win',
    init : function(){
        this.launcher = {
            text: 'Registry Editor',
            iconCls:'bogus',
            handler : this.createWindow,
            scope: this
        }
    },

    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('registryeditor-win');
        if(!win){
            win = desktop.createWindow({
                id: 'registryeditor-win',
                title:'Registry Editor',
                width:650,
                height:380,
                iconCls: 'bogus',
                shim:false,
                animCollapse:false,
                constrainHeader: true,
				maskDisabled:false,
				layout:'border',
				listeners: {'show': function() { dsRegistry.load({params:{root:"Registry", start:0, limit:50}});} },
                items:[
						{
							xtype:'treepanel',
							id:'tree-registry',
							width:200,
							title:'Registry',
							autoScroll:true,
							region:'west',
							split:true,
							useArrows: true,
							dataUrl:'MOBIMIN-AJAX/REGISTRY',
							requestMethod:'GET',
							listeners:{
								'click': function(node,event) {
										dsRegistry.load({params:{root:node.id,start:0, limit:50}})
								},
								'load': function(node) {
									//TODO
								}
							},
							root: {
								nodeType: 'async',
								text: 'Registry',
								id:'Registry'
							}
						},
						{
							xtype:'panel',
							layout:'fit',
							title:'Registry',
							region:'center',
							items: [{
								xtype:'grid',
								id:'grid-registry',
								tbar:{
									xtype:'toolbar',
									items:[
										{xtype:'button',
										id:'b-newregistry',
										text:'New',
										icon:'resources/images/access/tree/folder.gif',
										disabled:true,
										menu: new Ext.menu.Menu({
										items: [
											{text:'Key',icon:'images/reg_Key.png',handler:NewRegistryKey},
											{text:'String Value',icon:'images/reg_String.png',handler:NewRegistryString},
											{text:'DWORD Value',icon:'images/reg_DWORD.png',handler:NewRegistryDword},
											{text:'Binary Value',icon:'images/reg_Binary.png', handler:NewRegistryBinary},
											{text:'Multi-String Value',icon:'images/reg_MultiString.png',handler:NewRegistryMultiString},
											{text:'Expandable String Value',icon:'images/reg_ExpandString.png', handler:NewRegistryExpandableString}
											]
										}) //End of Split (new) Menu
										},
										{xtype:'button',id:'b-edit',disabled:true,text:'Edit',icon:'resources/images/access/tree/leaf.gif', handler:editRegistry},
										{xtype:'button',id:'b-delete',disabled:true,text:'Delete',icon:'resources/images/access/tree/drop-no.gif', handler:deleteRegistry}
									]
								},
								region:'center',
								loadMask:true,
								border:false,
								autoExpandColumn:true,
								columns: [
									{xtype:'templatecolumn',fixed:true,menuDisabled:true, sortable:false, dataIndex:'icon',width:28,tpl:'<img width="16px" src="images/reg_{type}.png" />'},
									{xtype:'gridcolumn', header:'Name', sortable:true, dataIndex:'name'},
									{xtype:'gridcolumn', header:'Type',sortable:true,dataIndex:'type'},
									{xtype:'gridcolumn', header:'Data', sortable: true, dataIndex:'data'}
								],
								ds:dsRegistry,
								bbar: {
										xtype:'paging',
										pageSize:50,
										store: dsRegistry,
										displayInfo:true,
										listeners:{'beforechange': function(p, options) { 
																	//options.params.root=store.lastOptions.root;
																	options.root=p.store.lastOptions.params.root;
																	return true;
																}
													}
										}, //End of bbar
								listeners: {
											'viewready': function(grid) {
												grid.getSelectionModel().on('rowselect', function(sm, rowIndex, r) {
													if (r.data.type=="Key") {
															grid.toolbars[0].items.items[1].setDisabled(true);
															grid.toolbars[0].items.items[2].setDisabled(false);
														} else {
															grid.toolbars[0].items.items[1].setDisabled(false);
															grid.toolbars[0].items.items[2].setDisabled(false);
														}
												  });
											}, //End of view ready
											'rowdblclick': function(grid,rowIndex,e) {
														if (this.store.data.items[rowIndex].data.type=="Key") {
															var parentFolder = this.store.lastOptions.params.root;
															var oTree = desktop.getWindow('registryeditor-win').items.items[0];
															oTree.getNodeById(parentFolder).expand(false,true, function(node) {
																node.ensureVisible();
																var folder= this.store.lastOptions.params.root + "/" + this.store.data.items[rowIndex].data.name;
																node.ownerTree.getNodeById(node.id + "/" + this.store.data.items[rowIndex].data.name).select();
																this.store.load({params:{root:folder,start:0, limit:50}});
																},
																this); //End of getNodeById
														} else {
															//TODO: Open file property window
														} //End if
											} //end of rowdblclick
										} //End of grid listeners
							}]
						}
						] //End of FileManager Items
            });
        }
        win.show();
    }
}); // End of Registry Manager window



MyDesktop.Outlook = Ext.extend(Ext.app.Module, {
    id:'outlook-win',
    init : function(){
        this.launcher = {
            text: 'Pocket Outlook',
            iconCls:'icon-grid',
            handler : this.createWindow,
            scope: this
        }
    },

    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('outlook-win');
        if(!win){
            win = desktop.createWindow({
                id: 'outlook-win',
                title:'Pocket Outlook',
                width:740,
                height:400,
                iconCls: 'icon-grid',
                shim:false,
                animCollapse:false,
                constrainHeader:true,
                layout: 'border',
                items:[
						{
							xtype:'panel',
							region:'west',
							split:true,
							width:200,
							border:false,
							layout:'accordion',
							layoutConfig: {
								animate: true,
								activeOnTop:false
							},
							items:[
									{
										title: 'Contacts',
										id:'action-contact',
										padding:4,
										defaults: {
											margins:4
										},
										items:[
											{
												xtype:'panel',
												frame:true,
												title: 'Contact Actions',
												collapsible:true,
												titleCollapse: true,
												html:'<img class="action-img" src="images/gears.gif" /><a id="action-newcontact" href=# onclick="return actionNewContact()">Add new contact</a><br /> <img class="action-img" src="images/gears.gif" /><a id="action-editcontact" href=# onclick="return actionEditContact()">Edit contact</a><br /><img class="action-img" src="images/gears.gif" /><a id="action-deletecontact" href=# onclick="return actionDeleteContact()">Delete contact</a>',
												bodyCfg: {
															handler: function() {alert(1);}
												}
											},
											{
												xtype:'panel',
												frame:true,
												title: 'Contact Grouping',
												collapsible:true,
												titleCollapse: true,
												html:'<a href=#>By Category</a>',
												bodyCfg: {
															handler: function() {alert(1);}
												}
											}
										],
										autoScroll:true,
										listeners: {
														'activate':function() {
																	dsGroupingContacts.load();
																	var grids = MyDesktop.desktop.getWindow('outlook-win'); //.items.items[1].items;
																	if (grids) {
																		ShowOutlookGrid(0);
																	}
																}
										}
									},
									{
										title: 'SMS',
										html:'<p>Something useful would be in here.</p>',
										autoScroll:true,
										listeners: {'activate':function() {
																ShowOutlookGrid(1);
																}
													
													}
									},
									{
										title: 'Tasks',
										html:'<p>Something useful would be in here.</p>',
										autoScroll:true,
										listeners: {'activate':function() {
																	dsTasks.load();
																	ShowOutlookGrid(2);
																}
													
													}
									},
									{
										title: 'Appointments',
										html:'<p>Something useful would be in here.</p>',
										autoScroll:true,
										listeners: {'activate':function() {
																	dsAppointments.load();
																	ShowOutlookGrid(3);
																}
													
													}
									}
									]
						},
						{
							xtype:'panel',
							region:'center',
							layout:'vbox',
							layoutConfig: {
								align : 'stretch',
								pack  : 'start'
							},
							border:false,
							items:[
									{
										xtype:'grid',
										id:'grid-contacts',
										title:'Contacts',
										region:'center',
										store:dsGroupingContacts,
										view: new Ext.grid.GroupingView({
													forceFit:true,
													groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Contacts" : "Contact"]})'
												}),
										hidden:false,
										flex:1,
										viewConfig:{forceFit:true},
										autoHeight:false,
										loadMask:true,
										cm: new Ext.grid.ColumnModel({
											columns: [ 
												{xtype:'gridcolumn',hidden:true,header:'itemId', dataIndex:'itemId'},
												{xtype:'templatecolumn', header:'Photo',width:55,fixed:true, resizable:false, tpl:'<img src="{contactPhoto}" width="45" />'},
												{xtype:'templatecolumn', header:'Full Name', tpl:'Name: <b>{fullName}</b><br /><i>{fileAs}</i>'},
												{xtype:'templatecolumn', header:'Phones',tpl:'<div><img src="images/email_go.png" /> {mobile}</div><div><img src="images/email_go.png" />{homePhone}</div>'},
												{xtype:'templatecolumn', header:'B. Phones', tpl:'<img src="images/email_go.png" />{businessPhone}<br /><img src="images/email_go.png" />{businessFax}'},
												{xtype:'templatecolumn', header:'URLs', tpl:'<img src="images/email_go.png" />{email}<br /><img src="images/email_go.png" />{webPage}'},
												{xtype:'gridcolumn',hidden:true,header:'Category', dataIndex:'category'}
											]
										})
									},
									{
										xtype:'grid',
										title:'SMS',
										region:'center',
										store:dsFiles,
										hidden:true,
										loadMask:true,
										flex:2,
										viewConfig:{forceFit:true},
										autoHeight:false,
										columns:[ 
											{xtype:'templatecolumn',header:'All Days', tpl:'{allDaysEvent}'},
											{xtype:'templatecolumn',header:'Description', tpl:'{body}'},
											{xtype:'templatecolumn',header:'Busy Status', tpl:'{busyStatus}'},
											{xtype:'templatecolumn',header:'Categories', tpl:'{categories}'},
											{xtype:'templatecolumn',header:'Duration', tpl:'{duration}'},
											{xtype:'templatecolumn',header:'Start', tpl:'{start}'},
											{xtype:'templatecolumn',header:'End', tpl:'{end}'},
											{xtype:'templatecolumn',header:'Location', tpl:'{locations}'}
										]
									},
									{
										xtype:'grid',
										title:'Tasks',
										id:'tasks-grid',
										region:'center',
										loadMask:true,
										store:dsTasks,
										hidden:true,
										flex:3,
										autoHeight:false,
										plugins: completeColumn,
										cm: new Ext.grid.ColumnModel({
											columns:[
												completeColumn,
												{xtype:'templatecolumn',header:'Subject', tpl:'{subject}'},
												{xtype:'templatecolumn',header:'Start Date', tpl:'{startDate}'},
												{xtype:'templatecolumn',header:'Due Date', tpl:'{dueDate}'},
												{xtype:'templatecolumn',header:'Priority', tpl:'{importance}',width:57,fixed:true},
												{xtype:'templatecolumn',header:'Sensitivity', tpl:'{sensitivity}',width:75},
												{xtype:'templatecolumn',header:'Categories', tpl:'{categories}',width:70,fixed:true},
												{xtype:'templatecolumn',header:'Description', tpl:'{body}'}
											]
										}),
										view: new Ext.grid.GridView({
											forceFit:true,
											ignoreAdd: true,
											markDirty:false,
											emptyText: 'No Tasks to display',
											getRowClass : function(r){
												var d = r.data;
												if(d.complete){
													return 'task-completed';
												}
												return '';
											}
										}), //End of view
										sm: new Ext.grid.RowSelectionModel({
											singleSelect:true
										})
									},
									{
										xtype:'grid',
										title:'Appointments',
										region:'center',
										loadMask:true,
										store:dsAppointments,
										hidden:true,
										flex:4,
										viewConfig:{forceFit:true},
										autoHeight:false,
										columns:[
											{xtype:'templatecolumn',header:'AllDays', tpl:'{allDaysEvent}',width:55,fixed:true},
											{xtype:'templatecolumn',header:'Subject', tpl:'<{dueStyle}>{subject}</{dueStyle}>'},
											{xtype:'templatecolumn',header:'Start', tpl:'{start}'},
											{xtype:'templatecolumn',header:'End', tpl:'{end}'},
											{xtype:'templatecolumn',header:'Duration', tpl:'{duration}',width:65,fixed:true},
											{xtype:'templatecolumn',header:'Categories', tpl:'{categories}', width:60},
											{xtype:'templatecolumn',header:'Location', tpl:'{location}'}
										]
									}
							]
						}
				]
				});
		}
		win.show();
	} //End of create window
});
// Aray data for the grid





Ext.grid.dummyData = [
    
    ['Wal-Mart Stores, Inc.',45.45,0.73,1.63,'9/1 12:00am'],
    ['Walt Disney Company (The) (Holding Company)',29.89,0.24,0.81,'9/1 12:00am']
];

var dsCallHistory = new Ext.data.JsonStore({
    // store configs
    autoDestroy: false,
	root:'rows',
	totalProperty: 'results',
	baseParams:{start:0, limit:50},
    proxy : new Ext.data.HttpProxy({
		method: 'GET',
		url: 'MOBIMIN-AJAX/CALLHISTORY'
		}),
    storeId: 'dsCallHistory',
    listeners: {'beforeload': function() {} },
    fields: ['name', 'number', 'startTime', 'endTime', 'callType', 'duration']
});

var dsOutgoingCalls = new Ext.data.JsonStore({
    // store configs
    autoDestroy: false,
	root:'rows',
	totalProperty: 'results',
	baseParams:{start:0, limit:50},
    proxy : new Ext.data.HttpProxy({
		method: 'GET',
		url: 'MOBIMIN-AJAX/OUTGOINGCALLS'
		}),
    storeId: 'dsOutgoingCalls',
    fields: ['name', 'number', 'startTime', 'duration']
});

var dsMissedCalls = new Ext.data.JsonStore({
    // store configs
    autoDestroy: false,
	root:'rows',
	totalProperty: 'results',
	baseParams:{start:0, limit:50},
    proxy : new Ext.data.HttpProxy({
		method: 'GET',
		url: 'MOBIMIN-AJAX/missedcalls'
		}),
    storeId: 'dsMissedCalls',
    fields: ['name', 'number', 'startTime', 'endTime']
});

var dsIncomingCalls = new Ext.data.JsonStore({
    // store configs
    autoDestroy: false,
	root:'rows',
	totalProperty: 'results',
	baseParams:{start:0, limit:50},
    proxy : new Ext.data.HttpProxy({
		method: 'GET',
		url: 'MOBIMIN-AJAX/incomingcalls'
		}),
    storeId: 'dsIncomingCalls',
    fields: ['name', 'number', 'startTime', 'duration']
});

var trayTaskMgr = {
	run: function() {
		//MyDesktop.desktop.taskbar.trayPanel.items.items[0].update('<img src="images/signal/wifi-on.png" title="' + Math.random() +  '" />');
		//MyDesktop.desktop.taskbar.trayPanel.items.items[0].setVisible(false);
		Ext.Ajax.request({
			url: 'MOBIMIN-AJAX/STATUS',
			success: function(response, opts) {
				var phoneStatus = Ext.decode(response.responseText);
				MyDesktop.desktop.taskbar.trayPanel.items.items[0].update('<img src="images/signal/wifi-on.png" title="' + phoneStatus.signal +  '" />');
				MyDesktop.desktop.taskbar.trayPanel.items.items[1].update('<img src="images/signal/wifi-on.png" title="' + phoneStatus.operatorName +  '" />');
				MyDesktop.desktop.taskbar.trayPanel.items.items[2].update('<img src="images/signal/wifi-on.png" title="' + phoneStatus.soundLevel +  '" />');
			},
			failure: function(response, opts) {
				//alert(response.status);
			}
		}); //End of ajax
	},	
	interval:10000
}


Ext.onReady(
	function() {
		//Ext.TaskMgr.start(trayTaskMgr);
	}
);
//

var dsFiles = new Ext.data.JsonStore({
    // store configs
    autoDestroy:false,
	root:'rows',
	totalProperty: 'results',
	baseParams: {root:'\/',start:0, limit:50},
	autoLoad:false,
	remoteSort:true,
	paramNames: {
		sort:'sortField',
		dir:'direction'
	},
	sortInfo: {
		field:'fileName',
		direction:'ASC'
	},
    proxy : new Ext.data.HttpProxy({
		method: 'GET',
		url: 'MOBIMIN-AJAX/FILES'
		}),
    storeId: 'dsFiles',
    fields:['fileName','creationTime','size','type','icon'],
	listeners: {
		'load': function(store,record,options) {
					var filePanel=MyDesktop.desktop.getWindow('filemanager-win').items.items[1];
					filePanel.setTitle(options.params.root);
					var girdFiles = filePanel.items.items[0];
					girdFiles.toolbars[0].items.items[1].setDisabled(true);
					girdFiles.toolbars[0].items.items[2].setDisabled(true);
					girdFiles.toolbars[0].items.items[3].setDisabled(true);
					girdFiles.toolbars[0].items.items[5].setDisabled(true);
					//girdFiles.toolbars[0].items.items[6].setDisabled(true);
				}
	}
});

var dsRegistry = new Ext.data.JsonStore({
    // store configs
    autoDestroy:false,
	root:'rows',
	totalProperty:'results',
	baseParams: {root:'Registry',start:0, limit:50},
	autoLoad:false,
    proxy : new Ext.data.HttpProxy({
		method: 'GET',
		url: 'MOBIMIN-AJAX/REGISTRYKEYS'
		}),
    storeId:'dsRegistry',
    fields:['name','type','data','editValue'],
	listeners: {
		'load': function(store,record,options) {
					var registryPanel=MyDesktop.desktop.getWindow('registryeditor-win').items.items[1];
					var gridRegistry = registryPanel.items.items[0];
					if (store.lastOptions.params.root=='Registry') {
						gridRegistry.toolbars[0].items.items[0].setDisabled(true);
					} else {
						gridRegistry.toolbars[0].items.items[0].setDisabled(false);
					}
					gridRegistry.toolbars[0].items.items[1].setDisabled(true);
					gridRegistry.toolbars[0].items.items[2].setDisabled(true);

				}
	}
});

var dsContacts = new Ext.data.JsonReader({
    // store configs
    autoDestroy:true,
	idProperty: 'itemId',
	root:'rows',
	totalProperty:'results',
	autoLoad:false,
    storeId:'dsContacts',
    fields:['itemId','fullName','mobile', 'jobTitle', 'company', 'fileAs', 'country', 'department', 'businessPhone', 'businessFax', 'homePhone', 'email', 'category', 'contactPhoto', 'nikeName', 'webPage'],
	listeners: {
		'load': function(store,record,options) {
					
				}
	}
});

var dsGroupingContacts = new Ext.data.GroupingStore({
	reader: dsContacts,
	storeId:'dsGroupingContacts',
	storeInfo:{field:'category', direction:"ASC"},
	autoLoad:false,
	groupField:'category',
	baseParams: {action:'contacts'},
	proxy : new Ext.data.HttpProxy({
		method: 'GET',
		url: 'MOBIMIN-AJAX/OUTLOOK'
		})
});

var dsAppointments = new Ext.data.JsonStore({
    // store configs
    autoDestroy: false,
	autoLoad:false,
	root:'rows',
	totalProperty: 'results',
	baseParams:{action:'appointments'},
    proxy : new Ext.data.HttpProxy({
		method: 'GET',
		url: 'MOBIMIN-AJAX/OUTLOOK'
		}),
    storeId: 'dsAppointments',
    listeners: {'beforeload': function() {} },
	fields: ['allDaysEvent', 'body', 'busyStatus', 'categories', 'duration', 'end','itemId','location','start','dueStyle','subject']
});

var dsTasks = new Ext.data.JsonStore({
    // store configs
    autoDestroy: false,
	autoLoad:false,
	root:'rows',
	totalProperty: 'results',
	baseParams:{action:'tasks'},
    proxy : new Ext.data.HttpProxy({
		method: 'GET',
		url: 'MOBIMIN-AJAX/OUTLOOK'
		}),
    storeId: 'dsTasks',
    listeners: {'beforeload': function() {} },
	fields: ['body','categories', 'complete', 'dueDate','itemId','importance','sensitivity','startDate','subject']
});

var dsCategories = new Ext.data.JsonStore({
	autoDestroy:false,
	autoLoad:false,
	root:'rows',
	totalProperty:'results',
	baseParams:{action:'categories'},
	proxy: new Ext.data.HttpProxy({
		method:'GET',
		url:'MOBIMIN-AJAX/OUTLOOK'
	}),
	fields:['categoryId', 'category']
});
//Functions

function propertyFF() {
	var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
	myMask.show();
	var parentFolder = dsFiles.lastOptions.params.root;
	var filePanel=MyDesktop.desktop.getWindow('filemanager-win').items.items[1];
	var gridFiles = filePanel.items.items[0];
	var row = gridFiles.selModel.selections.items[0].data;
	var data=row.fileName;
	var type=row.type;
	Ext.Ajax.request({
	url: 'MOBIMIN-AJAX/FILEMANAGER',
	params: { action:'property',parentFolder:parentFolder,data:data,type:type },
	method:'GET',
	success: function(response, opts) {
			var res = Ext.decode(response.responseText);
			if (res.success) {
				//refresh
				var pwin = new Ext.Window({
					title:data + ' Properties',
					modal:true,
					width:320,
					height:360,
					layout:'form',
					resizable:false,
					padding:10,
					buttons:[
						{xtype:'button', text:'OK', scope:this, handler:function() {pwin.close(); }}
					],
					labelWidth:75,
					defaults:{
						
					},
					items:[
						{xtype:'textfield',grow:true,fieldLabel:'File Name',readOnly:true,value:data},
						{xtype:'label',html:'<hr />'},
						{xtype:'label',fieldLabel:'Type',text:type},
						{xtype:'label',fieldLabel:'Location',text:res.fullName},
						{xtype:'label',fieldLabel:'Contains',text:res.filesCount+' Files, ' + res.directoriesCount + ' Folders',hidden:(type!='Folder')},
						{xtype:'label',fieldLabel:'Size',text:Ext.util.Format.fileSize(res.length),hidden:(type=='Folder')},
						{xtype:'label',html:'<hr />'},
						{xtype:'label',fieldLabel:'Created',text:res.creationTime},
						{xtype:'label',fieldLabel:'Modified',text:res.lastWriteTime},
						{xtype:'label',fieldLabel:'Accessed',text:res.lastAccessTime},
						{xtype:'label',html:'<hr />'},
						{xtype:'label',fieldLabel:'Attributes',text:res.attributes}
					],
					listeners:{
						'hide': function() {
							//MyDesktop.desktop.getWindow('filemanager-win').setDisabled(false);
						}
					}
				});
				pwin.show();
			} else {
				//MyDesktop.desktop.getWindow('filemanager-win').setDisabled(false);
			}
		myMask.hide()
	},
	failure: function(response, opts) {
		myMask.hide();
		alert(response.status);
	}
}); //End of ajax
}

function newFolder() {
	Ext.Msg.prompt('New Folder', 'Folder Name:', function(btn, text){
		if (btn == 'ok'){
			var parentFolder = dsFiles.lastOptions.params.root;
			Ext.Ajax.request({
				url: 'MOBIMIN-AJAX/FILEMANAGER',
				params: { action:'newfolder',parentFolder:parentFolder,data:text },
				method:'GET',
				success: function(response, opts) {
						var res = Ext.decode(response.responseText);
						if (res.success) {
							//refresh
							reloadNode();
							dsFiles.reload();
						} else {
						
						}
				},
				failure: function(response, opts) {
					alert(response.status);
				}
			}); //End of ajax
		}
	});
}

function deleteFF() {
	Ext.Msg.confirm('Delete', 'Are you sure you want to delete this folder/file?', function(btn, text){
		if (btn == 'yes'){
			var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Deleting ..."});
			myMask.show();
			var parentFolder = dsFiles.lastOptions.params.root;
			var filePanel=MyDesktop.desktop.getWindow('filemanager-win').items.items[1];
			var gridFiles = filePanel.items.items[0];
			var row = gridFiles.selModel.selections.items[0].data;
			var action= (row.type=='Folder'?'deletefolder':'deletefile');
			var data=row.fileName;
			Ext.Ajax.request({
				url: 'MOBIMIN-AJAX/FILEMANAGER',
				params: { action:action,parentFolder:parentFolder,data:data },
				method:'GET',
				success: function(response, opts) {
						var res = Ext.decode(response.responseText);
						if (res.success) {
							//refresh
							reloadNode();
							dsFiles.reload();
						} else {
						
						}
						myMask.hide();
				},
				failure: function(response, opts) {
					myMask.hide();
					alert(response.status);
				}
			}); //End of ajax
		}
	});
}

function reloadNode() {
	var parentFolder = dsFiles.lastOptions.params.root;
	var currentNode=MyDesktop.desktop.getWindow('filemanager-win').items.items[0].getNodeById(parentFolder);
	if (currentNode.expanded) {
		currentNode.reload();
	}
}

function reloadRegistryNode() {
	var parentRegistry = dsRegistry.lastOptions.params.root;
	var currentNode=MyDesktop.desktop.getWindow('registryeditor-win').items.items[0].getNodeById(parentRegistry);
	if (currentNode.expanded) {
		currentNode.reload();
	}
}

function renameFF() {
var fileName=MyDesktop.desktop.getWindow('filemanager-win').items.items[1].items.items[0].selModel.selections.items[0].data.fileName;
Ext.Msg.prompt('Rename', 'New Name:', function(btn, text){
if (btn == 'ok'){
	var parentFolder = dsFiles.lastOptions.params.root;
	var filePanel=MyDesktop.desktop.getWindow('filemanager-win').items.items[1];
	var gridFiles = filePanel.items.items[0];
	var row = gridFiles.selModel.selections.items[0].data;
	var action= (row.type=='Folder'?'renamefolder':'renamefile');
	var data=row.fileName;
	Ext.Ajax.request({
		url: 'MOBIMIN-AJAX/FILEMANAGER',
		params: { action:action,parentFolder:parentFolder,data:data,newName:text },
		method:'GET',
		success: function(response, opts) {
				var res = Ext.decode(response.responseText);
				if (res.success) {
					//refresh
					reloadNode();
					dsFiles.reload();
				} else {
				
				}
		},
		failure: function(response, opts) {
			alert(response.status);
		}
	}); //End of ajax
} // End if
}, this, false, fileName);
} //End Of Rename

function downloadFile(gzip) {
	var parentFolder = dsFiles.lastOptions.params.root;
	var filePanel=MyDesktop.desktop.getWindow('filemanager-win').items.items[1];
	var gridFiles = filePanel.items.items[0];
	var row = gridFiles.selModel.selections.items[0].data;
	var data=row.fileName;
	top.location.href='MOBIMIN-DOWNLOAD?_dc=8475638&parentFolder=' + parentFolder + "&fileName=" + data ;
} //end of function downloadFile


var wUpload;
function uploadFile() {
	wUpload= new Ext.Window({
		height: 112,
		width: 400,
		modal: true,
		layout:'fit',
		items:fileUploader,
		closeAction:'hide',
		resizable:false,
		title:'Uploadting to: ' + dsFiles.lastOptions.params.root
	});
	wUpload.show()
} //end of upload file

var fileUploader = new Ext.FormPanel({
        fileUpload:true,
        frame:true,
        autoHeight: true,
		border:true,
		bodyStyle: 'padding: 10px 10px 0 10px;',
        labelWidth: 35,
        defaults: {
			anchor:'95%',
            allowBlank: false,
            msgTarget: 'side'
        },
        items: [
			{
				xtype:'fileuploadfield',
				id:'form-file',
				emptyText:'Select a file',
				fieldLabel:'File',
				name:'file-path',
				buttonText:'...'
			}],
        buttons: [{
            text:'Save',
            handler: function(){
                if(fileUploader.getForm().isValid()){
	                fileUploader.getForm().submit({
	                    url:dsFiles.lastOptions.params.root,
	                    waitMsg: 'Uploading your file...',
	                    success: function(fp, o){
						    wUpload.hide();
							dsFiles.reload();
							Ext.Mobimin.msg('File Upload', 'File uploaded successfuly');
	                    }
	                });
                }
            }
        },{
            text: 'Reset',
            handler: function(){
                fileUploader.getForm().reset();
            }
        }]
    });

function deleteRegistry() {
Ext.Msg.confirm('Delete', 'Are you sure you want to delete this key/value?', function(btn, text){
if (btn == 'yes'){
	var parentNode = dsRegistry.lastOptions.params.root;
	var registryGrid = MyDesktop.desktop.getWindow('registryeditor-win').items.items[1].items.items[0];
	var row = registryGrid.selModel.selections.items[0].data;
	var type=row.type.toLowerCase();
	var text=row.name;
	Ext.Ajax.request({
				url: 'MOBIMIN-AJAX/REGISTRYMANAGER',
				params: { action:'delete',parentNode:parentNode,data:text,kind:type },
				method:'GET',
				success: function(response, opts) {
						var res = Ext.decode(response.responseText);
						if (res.success) {
							//refresh
							dsRegistry.reload();
							if (type=='key') {
								reloadRegistryNode();
							}
							Ext.Mobimin.msg('Delete Registry', 'Registry deleted successfuly');
						} else {
							//Ext.Mobimin.msg('Button Click', 'You clicked the {0} button', 1);
							alert(res.msg);
						}
				},
				failure: function(response, opts) {
					alert(response.status);
				}
	}); //End of ajax
}
});	
}

function renameRegistry() {

}	
	
function editRegistry() {
	var parentNode = dsRegistry.lastOptions.params.root;
	var registryGrid = MyDesktop.desktop.getWindow('registryeditor-win').items.items[1].items.items[0];
	var row = registryGrid.selModel.selections.items[0].data;
	var type=row.type.toLowerCase();
	NewRegistryValue(type, true, row);
}
function NewRegistryKey() {
	Ext.Msg.prompt('New Key', 'Key Name:', function(btn, text){
		if (btn == 'ok'){
			var parentNode = dsRegistry.lastOptions.params.root;
			Ext.Ajax.request({
				url: 'MOBIMIN-AJAX/REGISTRYMANAGER',
				params: { action:'newkey',parentNode:parentNode,data:text },
				method:'GET',
				success: function(response, opts) {
						var res = Ext.decode(response.responseText);
						if (res.success) {
							//refresh
							dsRegistry.reload();
							reloadRegistryNode();
							Ext.Mobimin.msg('New Key', 'Key created successfuly');
						} else {
							//Ext.Mobimin.msg('Button Click', 'You clicked the {0} button', 1);
							alert(res.msg);
						}
				},
				failure: function(response, opts) {
					alert(response.status);
				}
			}); //End of ajax
		}
	}); 
} // End of function RegistryKey 

function NewRegistryValue(kind,edit, row) {
var disableName=false;
var valueName="";
var valueValue="";
var titlePre='New';
if (edit) {
	disableName=true;
	valueName=row.name;
	valueValue=row.editValue;
	titlePre='Edit';
}
var isHex=true;
var fieldType = ( kind=='multistring' ? 'textarea' : 'textfield' );
var winTitle;
var emptyText;
var winHeight;
if (kind=='string') { winTitle=titlePre + ' String Value'; emptyText='String Value ...'; winHeight=140;}
if (kind=='dword') { winTitle=titlePre + ' DWord Value'; emptyText='DWord Number ...'; winHeight=160;}
if (kind=='binary') { winTitle=titlePre + ' Binary Value'; emptyText='Binary ie: 0F-00-1D ...'; winHeight=140;}
if (kind=='multistring') { winTitle=titlePre + ' Multi-String Value'; emptyText='String\nValue ...'; winHeight=180;}
if (kind=='expandablestring') { winTitle=titlePre + ' Expandable String Value'; emptyText='%Expandable% String ...';winHeight=140;}
var WinRegistry = new Ext.Window({
	width:300,
	height:winHeight,
	modal:true,
	title:winTitle,
	bodyStyle: 'padding: 10px 10px 0 10px;',
	layout:'form',
	resizable:false,
	labelWidth: 50,
        defaults: {
			anchor:'95%',
            allowBlank: false,
            msgTarget: 'side'
        },
	 items: [{
            xtype: 'textfield',
            fieldLabel:'Name',
			emptyText:'Value Name ...',
			disabled:disableName,
			value:valueName,
			allowBlank:true //For (Default) Value
        },{
			xtype:'radiogroup',
			hidden:(kind!='dword'),
			scope:this,
			listeners:{
				'change': function(rg,r) {
					isHex = !isHex;
					var txt = this.ownerCt.items.items[2];
					if (isHex) {
						txt.setValue(parseInt(txt.getValue()).toString(16));
					} else {
						txt.setValue(parseInt(txt.getValue(),16));
					}
				}
			},
			items: [
						{
							boxLabel:'Hex',
							name:'isHex',
							inputValue:true,
							checked:true
						},{
							boxLabel:'Decimal',
							name:'isHex',
							inputValue:false
						}
					]
		},{
            xtype:fieldType,
            fieldLabel:'Value',
			allowBlank:true,
			emptyText:emptyText,
			value:valueValue
        }],
	buttons:[{
				text:'Save',
				scope:this,
				handler: function() {
							var parentNode = dsRegistry.lastOptions.params.root;
							var ValueName=WinRegistry.items.items[0].getValue();
							var ValueData=WinRegistry.items.items[2].getValue();
							Ext.Ajax.request({
							url: 'MOBIMIN-AJAX/REGISTRYMANAGER',
							params: { kind:kind, action:'newvalue',parentNode:parentNode,valueName:ValueName,valueData:ValueData,extra:isHex },
							method:'GET',
							success: function(response, opts) {
									var res = Ext.decode(response.responseText);
									if (res.success) {
										//refresh
										WinRegistry.hide();
										dsRegistry.reload();
										Ext.Mobimin.msg('New Value', 'String created successfuly');
									} else {
										//Ext.Mobimin.msg('Button Click', 'You clicked the {0} button', 1);
										alert(res.msg);
									}
							},
							failure: function(response, opts) {
								alert(response.status);
							}
						}); //End of ajax
				}
			},{
				text:'Cancel',
				handler:function(){ WinRegistry.hide(); }
			}]
}); //End of WinRegistry
WinRegistry.show();
} // End of function NewValue 

function NewRegistryString() {
	NewRegistryValue('string');
} //End of NewRegistryString

function NewRegistryDword() {
	NewRegistryValue('dword');
} //End of NewRegistryDword

function NewRegistryMultiString() {
	NewRegistryValue('multistring');
}

function NewRegistryExpandableString() {
	NewRegistryValue('expandablestring');
}

function NewRegistryBinary() {
	NewRegistryValue('binary');
}

function ShowOutlookGrid(gridIndex) {
	var grids = MyDesktop.desktop.getWindow('outlook-win').items.items[1].items.items; 
	grids[0].setVisible(false);
	grids[1].setVisible(false);
	grids[2].setVisible(false);
	grids[3].setVisible(false);
	grids[gridIndex].setVisible(true);
	MyDesktop.desktop.getWindow('outlook-win').doLayout();
}

function actionNewContact() {
	var winContact = new Ext.Window({
		title:'New Contact',
		modal:true,
		width:300,
		height:485,
		resizable:false,
		layout:'fit',
		items:
			new Ext.FormPanel({
				url:'MOBIMIN-AJAX/OUTLOOK',
				method:'get',
				border:false,
				bodyBorder:false,
				hideBorders:true,
				layout:'fit',
				items:[
					{
						xtype:'tabpanel',
						activeTab:0,
						padding:5,
						autoHeight:false,
						deferredRender:false,
						items:[
							{
								title:'Personal',
								labelWidth:75,
								layout:'form',
								layoutConfig:{
									
								},
								defaults:{
									anchor:'100%'
								},
								items:[
									{xtype:'hidden', name:'action', value:'newcontact'},
									{xtype:'textfield', name:'firstName', fieldLabel:'First name'},
									{xtype:'textfield', name:'middle', fieldLabel:'Middle', anchor:'50%' },
									{xtype:'textfield', name:'lastName', fieldLabel:'Last name'},
									{xtype:'textfield', name:'mobile', fieldLabel:'Mobile'},
									{xtype:'textfield', name:'mainEmail', fieldLabel:'Main Email'},
									{xtype:'textfield', name:'im', fieldLabel:'IM'},
									{xtype:'datefield', name:'birthday', fieldLabel:'Birthday', format:'m/d/Y'},
									{
										xtype:'multiselect',
										name:'categories',
										fieldLabel:'Categories<br /><i>Ctrl + Click</i>',
										store:dsCategories,
										displayField:'category',
										valueField:'categoryId',
										width:195,
										allowBlank:true
									}
								]
							},
							{
								title:'Home',
								layout:'form',
								labelWidth:75,
								defaults:{
									anchor:'100%'
								},
								items:[
									{xtype:'textfield', name:'homePhone', fieldLabel:'Home Phone'},
									{xtype:'textfield', name:'homeFax', fieldLabel:'Home Fax'},
									{
										xtype:'panel',
										title:'Address',
										padding:5,
										frameBorder:false,
										layout:'table',
										layoutConfig:{
											columns:3,
											tableAttrs:{
												style:{
													width:'100%',
													cellpadding:3
												}
											}
										},
										defaults:{
											border:false,
										},
										items:[
											{
												colspan:3,
												html:'<span class="x-form-item">Street:</span>'
											},
											{
												colspan:3,
												layout:'form',
												border:false,
												items:[
													{xtype:'textfield', name:'homeStreet', hideLabel:true, width:260}
												]
											},
											{html:'<span class="x-form-item">City:</span>'},
											{html:'<span class="x-form-item">State:</span>'},
											{html:'<span class="x-form-item">Zip:</span>'},
											{xtype:'textfield', name:'homeCity', width:140},
											{xtype:'textfield', name:'homeState', width:50},
											{xtype:'textfield', name:'homeZip', width:60},
											{
												colspan:3,
												html:'<span class="x-form-item">Country:</span>'
											},
											{
												colspan:3,
												layout:'form',
												items:[
													{xtype:'textfield', name:'homeCountry', hideLabel:true, width:260}
												]
											}
										]
									} //end of home address
								]
							},
							{
								title:'Work',
								layout:'form',
								labelWidth:75,
								layoutConfig:{
									
								},
								defaults:{
									anchor:'100%'
								},
								items:[
									{xtype:'textfield', name:'company', fieldLabel:'Company'},
									{xtype:'textfield', name:'webPage', fieldLabel:'Web page'},
									{xtype:'textfield', name:'department', fieldLabel:'Department'},
									{xtype:'textfield', name:'jobTitle', fieldLabel:'Job Title'},
									{xtype:'textfield', name:'workTel', fieldLabel:'Work tel'},
									{xtype:'textfield', name:'workFax', fieldLabel:'Work fax'},
									{xtype:'textfield', name:'workEmail', fieldLabel:'Work Email'},
									{xtype:'datefield', name:'anniversary', fieldLabel:'Anniversary', format:'m/d/Y'},
									{
										xtype:'panel',
										title:'Work Address',
										padding:5,
										frameBorder:false,
										layout:'table',
										layoutConfig:{
											columns:3,
											tableAttrs:{
												style:{
													width:'100%',
													cellpadding:3
												}
											}
										},
										defaults:{
											border:false,
										},
										items:[
											{
												colspan:3,
												html:'<span class="x-form-item">Street:</span>'
											},
											{
												colspan:3,
												layout:'form',
												border:false,
												items:[
													{xtype:'textfield', name:'workStreet', hideLabel:true, width:260}
												]
											},
											{html:'<span class="x-form-item">City:</span>'},
											{html:'<span class="x-form-item">State:</span>'},
											{html:'<span class="x-form-item">Zip:</span>'},
											{xtype:'textfield', name:'workCity', width:140},
											{xtype:'textfield', name:'workState', width:50},
											{xtype:'textfield', name:'workZip', width:60},
											{
												colspan:3,
												html:'<span class="x-form-item">Country:</span>'
											},
											{
												colspan:3,
												layout:'form',
												items:[
													{xtype:'textfield', name:'workCountry', hideLabel:true, width:260}
												]
											}
										]
									} //end of work address
								]
							},
							{
								title:'Notes',
								layout:'fit',
								items:[
									{xtype:'textarea', name:'notes'}
								]
							}
						]
					}
				],
			buttons:[
				{
					xtype:'button',
					text:'Save',
					handler:function(oW) {
								var frm=this.ownerCt.ownerCt.getForm();
								frm.submit({
									waitMsg: 'Saving ...',
									success: function(fp, o){
											Ext.Mobimin.msg('New Contact', 'New Contact created successfuly');
											oW.ownerCt.ownerCt.ownerCt.close();
											dsGroupingContacts.reload();
										}
									});
							}
					},
				{
					xtype:'button',
					text:'Cancel',
					handler:function(oW) {
						oW.ownerCt.ownerCt.ownerCt.close();
					}
				}
			]
		}), //End of FormPanel
	});
	dsCategories.load();
	winContact.show();
	return false;
} //action new Contact

function actionDeleteContact() {
	var gridOutlook = Ext.getCmp('grid-contacts');
	var row = gridOutlook.selModel.selections.items[0].data;
	Ext.Msg.confirm('Delete', 'Are you sure you want to delete <b>' + row.fullName + '</b>?', function(btn, text){
		if (btn == 'yes'){
			Ext.Ajax.request({
				url: 'MOBIMIN-AJAX/OUTLOOK',
				params: { action:'deletecontact',itemId:row.itemId },
				method:'GET',
				success: function(response, opts) {
						var res = Ext.decode(response.responseText);
						if (res.success) {
							//refresh
							dsGroupingContacts.reload();
							//reloadRegistryNode();
							Ext.Mobimin.msg('Delete Contact', 'Contact deleted successfuly');
						} else {
							//Ext.Mobimin.msg('Button Click', 'You clicked the {0} button', 1);
							alert(res.msg);
						}
				},
				failure: function(response, opts) {
					alert(response.status);
				}
			}); //End of ajax
		}
	});
	return false;
}

//Plugins

 var completeColumn = new CompleteColumn();
